package com.sf.dlb.service;

import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.AppVersionInfo;
import com.sf.dlb.jpa.repository.AppVersionRepository;
import com.sf.dlb.config.Global;
import com.sf.dlb.utils.ResultVOUtil;
import com.sf.dlb.utils.StateToValueUtils;
import com.sf.dlb.vo.AppVersionVO;
import com.sf.dlb.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by jing.tan on 2018/5/21.
 */
@Service
public class AppVersionService {
    private static Logger logger = LoggerFactory.getLogger(AppVersionService.class);

    @Autowired
    private AppVersionRepository appVersionRepository;
    @Resource
    private Global global;

    /**
     * 获取APP版本信息
     * @return
     */
    public ResultVO findBySystemType(String stystemType){
        logger.info(" findBySystemType stystemType={}",stystemType);
        List<AppVersionInfo> appVersionInfos=appVersionRepository.findBySystemTypeAndDelFlag(stystemType,"0");
        if(CollectionUtils.isEmpty(appVersionInfos)){
            logger.info(" findBySystemType appVersionInfos is null ");
            return ResultVOUtil.error(ResponseConstant.ERROR,"暂无版本信息");
        }
        //返回最新版本
        AppVersionInfo appVersionInfo=appVersionInfos.get(0);
        AppVersionVO appVersionVO = new AppVersionVO();
        BeanUtils.copyProperties(appVersionInfo, appVersionVO);
        String downloadUrl=appVersionInfo.getDownloadUrl();
        //如果是android，需要添加IP前缀
        if(appVersionInfo.getSystemType().equals("1")){
            downloadUrl = global.file_public_ip+appVersionVO.getDownloadUrl();
        }
        appVersionVO.setDownloadUrl(downloadUrl);
        appVersionVO.setStystemTypeValue(StateToValueUtils.switchAppVersionValue(appVersionVO.getSystemType()));
        appVersionVO.setCreateDate(appVersionInfo.getCreateDate().getTime());
        return ResultVOUtil.success(appVersionVO);
    }
}
